const Router = require('koa-router')
const parse = require('co-body')
const amqp = require('amqplib')
const uuid = require('node-uuid')
const when = require('when')

const router = new Router()
const defer = when.defer

const q = process.env.QUEUE_NAME

router.post('/send/emails', function* () {
  const body = yield parse(this)
  const conn = yield amqp.connect(process.env.RABBITMA_CONNECTION)
  const ch = yield conn.createChannel()
  // should identical to consumer
  ch.assertQueue(q)
  // ch.assertQueue(q, { durable: true })
  ch.sendToQueue(q, new Buffer(body.email))
  this.body = { op: 'op' }
})

// with generator yield
router.post('/send/emails/yield', function* () {
  const body = yield parse(this)

  const conn = yield amqp.connect('amqp://localhost')
  const ch = yield conn.createChannel()

  const answer = defer()
  const corrId = uuid()
  function maybeAnswer(msg) {
    if (msg.properties.correlationId === corrId) {
      answer.resolve(msg.content.toString());
    }
  }

  let data = yield ch.assertQueue('', { exclusive: true })
    .then((qok) => {
      return qok.queue
    })
    .then((queue) => {
      return ch.consume(queue, maybeAnswer, { noAck: true })
        .then(() => {
          return queue
        })
    })
    .then((queue) => {
      ch.sendToQueue(process.env.QUEUE_NAME, new Buffer(body.email.toString()), {
        correlationId: corrId, replyTo: queue
      })
      return answer.promise
    })
    .then((rs) => {
      return rs
    })

  this.type = 'json'
  this.body = data
})

module.exports = router
